<template>
  <div class="template-editor-container">
    <!-- 顶部工具栏 -->
    <div class="editor-toolbar">
      <button @click="saveTemplate" class="save-btn">保存模板</button>
      <button @click="togglePreview" class="preview-btn">
        {{ showPreview ? '返回编辑' : '预览效果' }}
      </button>
    </div>

    <!-- 编辑区域 -->
    <div class="editor-area" v-if="!showPreview">
      <div class="editor-section">
        <h3>文书内容编辑</h3>
        <QuillEditor
            v-model:content="template.content"
            contentType="html"
            :options="editorOptions"
            @textChange="extractVariables"
        />
      </div>

      <div class="variables-section">
        <h3>变量管理</h3>
        <div class="variable-list">
          <div v-for="(varItem, index) in template.variables" :key="index" class="variable-item">
            <div class="var-name">{{ varItem.key }}</div>
            <input
                v-model="varItem.name"
                placeholder="变量显示名称"
                class="var-input"
            >
            <input
                v-model="varItem.defaultValue"
                placeholder="默认值"
                class="var-input"
            >
            <button @click="removeVariable(index)" class="remove-btn">×</button>
          </div>
        </div>

        <div class="variable-test">
          <h4>测试变量填充</h4>
          <button @click="testFillVariables" class="test-btn">填充测试数据</button>
        </div>
      </div>
    </div>

    <!-- 预览区域 -->
    <div class="preview-area" v-else>
      <div class="preview-container" v-html="previewContent"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import axios from 'axios'

// 模板数据结构
const template = ref({
  id: null,
  name: '',
  type: '',
  content: '',
  variables: []
})

// 编辑器配置
const editorOptions = {
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'script': 'sub'}, { 'script': 'super' }],
      [{ 'indent': '-1'}, { 'indent': '+1' }],
      [{ 'direction': 'rtl' }],
      [{ 'size': ['small', false, 'large', 'huge'] }],
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['clean'],
      ['link', 'image', 'video']
    ]
  },
  placeholder: '请输入文书内容...',
  theme: 'snow'
}

// 提取变量
const extractVariables = () => {
  const content = template.value.content
  const variableRegex = /\{(\w+)\}/g
  const matches = [...new Set([...content.matchAll(variableRegex)].map(m => m[1]))]

  // 保留已有变量的配置
  const existingVars = template.value.variables.reduce((acc, v) => {
    acc[v.key] = v
    return acc
  }, {})

  template.value.variables = matches.map(key => {
    return existingVars[key] || {
      key,
      name: key,
      defaultValue: '',
      description: ''
    }
  })
}

// 测试填充变量
const testFillVariables = () => {
  const testValues = {
    applicantName: '张三',
    applicantGender: '男',
    applicantIdCard: '110101199001011234',
    // 其他测试数据...
  }

  template.value.variables.forEach(v => {
    if (testValues[v.key]) {
      v.defaultValue = testValues[v.key]
    }
  })
}

// 预览功能
const showPreview = ref(false)
const previewContent = computed(() => {
  let content = template.value.content
  template.value.variables.forEach(v => {
    const regex = new RegExp(`\\{${v.key}\\}`, 'g')
    content = content.replace(regex, v.defaultValue || `[${v.name}]`)
  })
  return content
})

const togglePreview = () => {
  showPreview.value = !showPreview.value
}

// 保存模板
const saveTemplate = async () => {
  try {
    const payload = {
      ...template.value,
      variables: JSON.stringify(template.value.variables)
    }

    const url = template.value.id
        ? `/api/templates/${template.value.id}`
        : '/api/templates'

    const method = template.value.id ? 'put' : 'post'

    const { data } = await axios[method](url, payload)

    if (!template.value.id) {
      template.value.id = data.id
    }

    alert('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    alert('保存失败，请重试')
  }
}

// 加载模板
const loadTemplate = async (templateId) => {
  if (!templateId) return

  try {
    const { data } = await axios.get(`/api/templates/${templateId}`)
    template.value = {
      ...data,
      variables: JSON.parse(data.variables || '[]')
    }
  } catch (error) {
    console.error('加载模板失败:', error)
  }
}

// 初始化
onMounted(() => {
  const templateId = route.params.id
  loadTemplate(templateId)
})
</script>

<style scoped>
.template-editor-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.editor-toolbar {
  padding: 10px;
  background-color: #2c3e50;
  display: flex;
  gap: 10px;
}

.save-btn, .preview-btn {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.preview-btn {
  background-color: #3498db;
}

.editor-area {
  display: flex;
  flex: 1;
  padding: 20px;
  gap: 20px;
}

.editor-section {
  flex: 2;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.variables-section {
  flex: 1;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.variable-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 8px;
}

.var-name {
  min-width: 80px;
  font-weight: bold;
  color: #2c3e50;
}

.var-input {
  flex: 1;
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.remove-btn {
  background-color: #e74c3c;
  color: white;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
}

.preview-area {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.preview-container {
  background-color: white;
  padding: 40px;
  min-height: 100%;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
</style>